using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Magiq.Databases.Delete
{
    public class DeleteCommandBuilder<T> : CommandBuilder
    {
        private readonly IQueryable<T> typedWhere;
        public DeleteCommandBuilder(IOrmAdapter ormAdapter, IQueryable<T> where)
            : base(ormAdapter, where, true)
        {
            typedWhere = where;
            Init(typeof(T));
        }

        private Expression<Func<T,IdHelper>> GetSelectExpression()
        {
            var parameter = Expression.Parameter(typeof (T));
            // x.Prop
            var entityId = Expression.Property(parameter, TypeReferenceProperty.PropertyName);
            // PropertyXXXXX = x.Prop
            var bind = Expression.Bind(IdHelperIdProperty, entityId);
            // new IdHelper{ PropertyXXXXX = x.Prop }
            var select = Expression.MemberInit(Expression.New(typeof (IdHelper)), bind);

            return Expression.Lambda<Func<T, IdHelper>>(select, parameter);
        }

        public override IDbCommand GetCommand()
        {
            Command.CommandText = OrmAdapter.Dialect.DeleteClauseFor(BaseTableName, From);
            return Command;
        }

        private static readonly MemberInfo IdHelperIdProperty = typeof(IdHelper).GetProperty("PropertyXXXXX");
        private class IdHelper
        {
            public object PropertyXXXXX { get; set; }
        }
        protected override void Init(Type elementType)
        {
            base.Init(elementType);
            var select = GetSelectExpression();
            var query = typedWhere.Select(select);
            SetCommand(OrmAdapter.GetSelectCommand(query),query);
        }
    }

    
}